const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const code = fs.readdirSync('./code');

const entry = _.reduce(
  code,
  (t, name) => {
    const key = name.match(/\w+/)[0];
    return _.set(t, key, path.resolve(__dirname, `code/${name}`));
  },
  {}
);
const apps = _.keys(entry);
const plugins = [].concat(
  _.map(
    apps,
    (app) =>
      new HtmlWebpackPlugin({
        title: app,
        chunks: [app],
        filename: `${app}.html`,
        template: 'index.html',
        html: `<ul>
          ${_.map(
            apps,
            (name) => `<li><a href="${name}.html">${name}</a></li>`
          ).join('')}
        </ul>`,
      })
  )
);

const config = {
  mode: 'development',
  entry,
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
};

module.exports = config;
